﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using Log;

namespace RegLog
{
    public class LogEventView : ILog
    {
        private string NomeLog { get; set; }
        private EventLog LogView;

        public LogEventView(string nomeLog)
        {
            NomeLog = string.IsNullOrWhiteSpace(nomeLog) ? "RegistroLog" : nomeLog;
            RegistrarLog();
        }

        private void RegistrarLog()
        {
            LogView = new EventLog(NomeLog);
            LogView.Source = NomeLog;
            LogView.Log = NomeLog;
            if (!EventLog.SourceExists(NomeLog))
                EventLog.CreateEventSource(NomeLog, NomeLog);
        }

        public void Log(object sender, EventosLogEventArgs e, out int ret)
        {
            try
            {
                if (LogView == null) RegistrarLog();
                EventLogEntryType tipo;
                switch (e.TipoLog)
	            {
		            case GrauCritico.Sucesso: tipo = EventLogEntryType.SuccessAudit;
                        break;
                    case GrauCritico.Informacao: tipo = EventLogEntryType.Information;
                        break;
                    case GrauCritico.Alerta: tipo = EventLogEntryType.Warning;
                        break;
                    case GrauCritico.Falha: tipo = EventLogEntryType.FailureAudit;
                        break;
                    case GrauCritico.Erro: tipo = EventLogEntryType.Error;
                        break;
                    case GrauCritico.ErroCritico: tipo = EventLogEntryType.Error;
                        break;
                    case GrauCritico.Debug: tipo = EventLogEntryType.Information;
                        break;
                    default: tipo = EventLogEntryType.Information;
                        break;
	            }

                string excecao = e.Exception.Message + Environment.NewLine + e.Exception.Source + Environment.NewLine + e.Exception.StackTrace + Environment.NewLine + e.Exception.TargetSite.ToString();
                byte[] bytes = Encoding.ASCII.GetBytes(excecao);
                
                LogView.WriteEntry(e.Descricao, tipo, 0, (short)e.TipoLog, bytes);
                ret = 0;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
